__author__ = 'weixin.yuan'
__data__ = '2019-06-29'
"""
ui自动化测试框架入口
"""

import sys
import uiautomator2 as u2
from lib.HTMLTestRunner_cn import HTMLTestRunner
from config.settings import *
from utils.log import log
from utils.initialize import *
from utils.schema import Schema
from suite import suite_adr, suite_ios
import utils.global_var as gl
from utils.mysqlUtil import insert_mysql

args = sys.argv
build_tag = args[1]  # 构建编号
device_type = args[2]
ip = args[3]  # ip
cases = args[4]  # 用例列表
if len(args) == 5:
    build_user = ''
else:
    build_user = args[5]


logger = log('train')  # 初始化日志


def generate_runner(title, description):
    fp = __generate_report()
    runner = HTMLTestRunner(title=title,
                            description=description,
                            stream=fp,
                            verbosity=0,
                            retry=1,
                            save_last_try=True)
    return runner


def __generate_report():
    report_name = '/train_' + build_tag + '.html'
    html_report_path = REPORT + report_name  # 测试报告绝对路径
    logger.info('生成测试报告：%s' % html_report_path)
    fp = open(html_report_path, 'wb')  # 打开测试报告文件
    logger.info('测试报告地址：http://100.81.136.54:9000/report/%s' % report_name)
    return fp


def init_anr_device(device_ip, schema_file):
    logger.info('创建连接，设备ip:%s' % device_ip)
    logger.info(device_ip.strip())
    logger.info(type(device_ip.strip()))
    d = u2.connect(device_ip.strip())  # 创建连接
    logger.info('初始化设备...')
    screen_status = d.info.get('screenOn')
    if not screen_status:
        d.screen_on()  # 亮屏
        d.unlock()  # 解锁
    d.press("home")  # 点击home键
    logger.info('push apk to %s' % device_ip)
    # d.app_install('http://100.81.136.54:9000/apk/testdemo.apk')  # 安装apk
    d.app_stop_all()  # 停止所有后台app
    d.set_fastinput_ime(True)  # 设置输入法
    d.healthcheck()  # 监控检查
    logger.info('push schema.txt to %s' % device_ip)
    d.push(schema_file, "/storage/emulated/0/schemaurls.txt", mode=0o755)  # push schema文件


def save_result_to_mysql(result):
    """
    保存测试结果至数据库
    :param result:
    :return:
    """
    success_count = int(result.success_count)
    error_count = int(result.error_count)
    failure_count = int(result.failure_count)
    case_total = success_count + error_count + failure_count

    if case_total != success_count:
        result = "Failed"
    else:
        result = "Success"
    # ('qunar', 15, 15, 0, 0, '成功', '测试报告地址', '创建时间')
    report_name = '/train_' + build_tag + '.html'
    report_path = 'http://100.81.136.54:9000/report/' + report_name
    create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    data = (
        build_user,
        case_total,
        success_count,
        failure_count,
        error_count,
        result,
        report_path,
        create_time
    )

    insert_mysql(data=data)


def run():
    logger.info('start ui auto test...')

    logger.info('本次运行测试用例:%s' % str(cases.split(',')))
    if device_type == 'anr':
        logger.info('测试设备：%s，设备类型：%s' % (ip, device_type))
        suite = suite_adr.generate_suite(cases)
        Schema(SCHEMA_FILE_ADR, device_type).run()  # 处理schema文件
        init_anr_device(ip, SCHEMA_FILE_ADR)  # 初始化设备
        # 设置全局变量
        gl.init()
        gl.set_value('ip', ip)
    else:
        start_wda_server()
        suite = suite_ios.generate_suite(cases)
        Schema(SCHEMA_FILE_IOS, device_type).run()  # 处理schema文件

    try:
        logger.info('开始执行测试用例脚本...')
        runner = generate_runner(title=u"去哪儿网火车票ui自动化测试报告", description=u'测试环境beta包crash测试')
        result = runner.run(suite)  # 运行测试套件

        if build_tag != 'localhost' and build_user != '':
            # 测试结果入库
            save_result_to_mysql(result)
        logger.info('结束执行测试用例脚本。')
    except Exception as e:
        logger.error('运行脚本发生错误，错误信息：%s' % str(e))
    finally:
        logger.info('end ui auto test...')


if __name__ == '__main__':
    run()  # 入口
